package com.zhongwang.mms.module.material.controller;

import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.module.material.dao.MReportFormsDao;
import com.zhongwang.mms.module.material.model.*;
import com.zhongwang.mms.module.material.service.MReportFormsService;
import com.zhongwang.mms.module.overview.dao.OveIndexDao;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 原料统计报表 控制层
 * @Author: China.wsg
 * @Date: 2020/06/09
 */

@Controller
@RequestMapping("/material/reportForms")
public class MReportFormsController extends BaseController {

    @Autowired
    private MReportFormsDao reportFormsDao;
    @Autowired
    private MReportFormsService mReportFormsService;
    @Autowired
    private OveIndexDao oveIndexDao;

    /**
     * 首页图标跳转
     * @param model
     * @param type
     * @return
     */
    @GetMapping("/lists/{type}/{year}/{month}")
    public String lists(Model model, @PathVariable("type") Integer type, @PathVariable("year") Integer year, @PathVariable("month") Integer month){
        Date date = new Date();
        date.setMonth(month);
        Calendar ct = Calendar.getInstance();
        ct.setTime(date);
        ct.set(Calendar.DAY_OF_MONTH, 1);
        Date startDate = ct.getTime();
        ct.set(Calendar.DAY_OF_MONTH, ct.getActualMaximum(Calendar.DAY_OF_MONTH));
        //月最后一天
        Date endDate = ct.getTime();
       /* ct.add(Calendar.MONTH, + 1);
        Date endDate = ct.getTime();*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String st = format.format(startDate);
        st = st.replace(st.substring(0,st.indexOf("-")),year.toString());
        String et = format.format(endDate);
        et = et.replace(et.substring(0,et.indexOf("-")),year.toString());
        if(type == 1){//入库量
            model.addAttribute("inOutType",1);//入库
            model.addAttribute("odrType",1);//采购入库
            model.addAttribute("startDate",st);
            model.addAttribute("tittle",1);
            model.addAttribute("endDate",et);
            return "reportForms/matInWar/list";
        }else if(type == 2){//出库量
            model.addAttribute("inOutType",2);//出库
            model.addAttribute("odrType",4);//领料出库
            model.addAttribute("startDate",st);
            model.addAttribute("tittle",2);
            model.addAttribute("endDate",et);
            return "reportForms/matInWar/list";
        }else if(type == 5){//返料量
            model.addAttribute("inOutType",1);//入库
            model.addAttribute("odrType",2);//退料入库
            model.addAttribute("startDate",st);
            model.addAttribute("tittle",3);
            model.addAttribute("endDate",et);
            return "reportForms/matInWar/list";
        }else if(type == 3){
            model.addAttribute("inOutType",2);//出库
            model.addAttribute("odrType",4);//领料出库
            model.addAttribute("startDate",st);
            model.addAttribute("endDate",et);
            return "reportForms/matInWar/list1";
        }else if(type == 4){
            model.addAttribute("pimAppStatus",3);//已执行
            model.addAttribute("startDate",st);
            model.addAttribute("endDate",et);
            return "reportForms/matInWar/list2";
        }
        return null;
    }

    /**
     * 消耗库存量列表数据
     *
     * @param compositeOutcomeModel 查询条件
     * @return list
     */
    @ResponseBody
    @PostMapping("/list")
    public JsonResult list(CompositeOutcomeModel compositeOutcomeModel) {
        startPage();
        List<CompositeOutcomeModel> list = reportFormsDao.findConsumedInventory(compositeOutcomeModel);
        return jsonResult(list);
    }
    /**
     * 消耗库存量列表 导出
     * @param compositeOutcomeModel 查询条件
     * @return list
     */
    @GetMapping("/exportExcel")
    @ResponseBody
    @RequiresPermissions({"matwar:matwarquery:export"})
    public void exportExcel(HttpServletResponse response, CompositeOutcomeModel compositeOutcomeModel) {
        mReportFormsService.exportExcel(response,compositeOutcomeModel);
    }

    /**
     * 项目剩余量页面
     *
     * @return 页面路径
     */
    @GetMapping("/matResidue")
    public String project() {
        return "reportForms/matResidue/list";
    }
    /**
     * 项目剩余量页面
     *
     * @return 页面路径
     */
    @GetMapping("/matYingKouInvClassDetails")
    public String matYingKouInvClassDetails() {
        return "overview/statisticalReport/matYingKouInvClassDetails/page";
    }

    /**
     * 项目剩余量列表
     *
     * @param residueModel 查询条件
     * @return
     */
    @ResponseBody
    @PostMapping("/matResidueList")
    public JsonResult list(MResidueModel residueModel) {
        startPage();
        List<MResidueModel> list = reportFormsDao.findResidueModel(residueModel);
        return jsonResult(list);
    }

    /**
     * 机械月出库总表
     *
     * @return 页面路径
     */
    @GetMapping("/matMechanicsOutWar")
    public String matMechanicsOutWar() {
        return "reportForms/matMechanicsOutWar/list";
    }

    /**
     * 机械月出库总表列表数据
     *
     * @param param
     * @return
     */
    @ResponseBody
    @PostMapping("/matMechanicsOutWarList")
    public JsonResult matMechanicsOutWarList(MechanicsOutWar param) {
        startPage();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(param.getEndOdrDate());
        calendar.add(Calendar.DATE, 1);
        param.setEndOdrDate(calendar.getTime());
        List<MechanicsOutWar> list = reportFormsDao.findMatMechanicsOutWarList(param);
        return jsonResult(list);
    }

    /**
     * 机械月出库总表列表数据导出
     *
     * @param response
     * @param param
     */
    @ResponseBody
    @GetMapping("/matMechanicsOutWarExcel")
    public void matMechanicsOutWarExcel(HttpServletResponse response, MechanicsOutWar param) {
        mReportFormsService.matMechanicsOutWarExcel(response, param);
    }

    /**
     * 外厂月出库总表
     *
     * @return 页面路径
     */
    @GetMapping("/matOutFactoryOutWar")
    public String matOutFactoryOutWarList() {

        return "reportForms/matOutFactoryOutWar/list";
    }

    /**
     * 外厂月出库总表列表数据
     *
     * @param param
     * @return
     */
    @ResponseBody
    @PostMapping("/matOutFactoryOutWarList")
    public JsonResult matOutFactoryOutWarList(MechanicsOutWar param) {
        startPage();
        if(param.getEndOdrDate()!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(param.getEndOdrDate());
            calendar.add(Calendar.DATE, 1);
            param.setEndOdrDate(calendar.getTime());
        }
        List<MechanicsOutWar> list = reportFormsDao.findmMatOutFactoryOutWarList(param);
        return jsonResult(list);
    }

    /**
     * 外厂出库导出
     * @param response
     * @param param
     */
    @ResponseBody
    @GetMapping("/matOutFactoryOutWarExcel")
    public void matOutFactoryOutWarExcel(HttpServletResponse response, MechanicsOutWar param) {
        mReportFormsService.matOutFactoryOutWarExcel(response, param);
    }

    /**
     * 不常用库存
     * @return
     */
    @GetMapping("/matInfrequentStock")
    public String matInfrequentStock() {
        return "reportForms/matInfrequentStock/page";
    }

    /**
     * 不常用库存列表
     * @param complexStorageModel
     * @param matTypeIdList
     * @param matQualityIdList
     * @param matSpecIdList
     * @return
     */
    @ResponseBody
    @PostMapping("/matInfrequentStockList")
    public JsonResult list(ComplexStorageModel complexStorageModel, @RequestParam(value = "matTypeIdList[]", required = false) List<String> matTypeIdList,
                           @RequestParam(value = "matQualityIdList[]", required = false) List<String> matQualityIdList,
                           @RequestParam(value = "matSpecIdList[]", required = false) List<String> matSpecIdList) {
        startPage();
        List<MatInfrequentStockExport> list = mReportFormsService.findStorage(complexStorageModel, matTypeIdList, matQualityIdList, matSpecIdList);
        return jsonResult(list);
    }

    /**
     * 不常用库存导出
     */
    @ResponseBody
    @GetMapping("/matInfrequentStockExportExcel")
    public void matInfrequentStockExportExcel(HttpServletResponse response, ComplexStorageModel complexStorageModel, @RequestParam(value = "matTypeIdList[]", required = false) List<String> matTypeIdList,
                                              @RequestParam(value = "matQualityIdList[]", required = false) List<String> matQualityIdList,
                                              @RequestParam(value = "matSpecIdList[]", required = false) List<String> matSpecIdList) {
        mReportFormsService.matInfrequentStockExportExcel(response, complexStorageModel, matTypeIdList, matQualityIdList, matSpecIdList);
    }

    /**
     * 阶段报表
     * @return
     */
    @GetMapping("/matStageReport")
    public String matStageReport() {
        return "reportForms/matStageReport/list";
    }
    /**
     * 项目回货总表
     * @param param
     * @return
     */
    @ResponseBody
    @PostMapping("/matStageReportList")
    public JsonResult matStageReportList(MatStageReportModel param) {
        List<MatStageReportModel> list = reportFormsDao.findMatStageReportList(param);
        return jsonResult(list);
    }

    /**
     * 阶段报表导出
     * @param response
     * @param param
     */
    @ResponseBody
    @GetMapping("/matStageReportExcel")
    public void matStageReportExcel(HttpServletResponse response, MatStageReportModel param) {
        mReportFormsService.matStageReportExcel(response, param);
    }

    /**
     * 物资明细
     * @return
     */
    @GetMapping("/matDetail")
    public String matDetail(Model model) {

        //项目在库里项目编号为150000的钢材总量
        BigDecimal weight = reportFormsDao.selectSpecialSum().divide(BigDecimal.valueOf(1000),BigDecimal.ROUND_HALF_UP);
        model.addAttribute("nowTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        model.addAttribute("inProSteel",oveIndexDao.getRawMaterialProjectTotalWeight().subtract(weight));//在干项目钢材总量
        model.addAttribute("stopProSteel",oveIndexDao.getRawMaterialBoardTotalWeight().add(oveIndexDao.getRawMaterialProfileTotalWeight()).add(weight));//暂缓项目钢材总量
        model.addAttribute("spareParts",oveIndexDao.getRawMaterialSparePartTotalWeight());//机械常用备件
        model.addAttribute("allSteelWeight",oveIndexDao.getRawMaterialSteelTotalWeight());//钢材总重量
        return "reportForms/matDetail/detail";
    }

    /**
     * 物资明细导出
     * @param model
     * @return
     */
    @GetMapping("/matDetailExcel")
    public void matDetailExcel(Model model, HttpServletResponse response) {

        //项目在库里项目编号为150000的钢材总量
        BigDecimal weight = reportFormsDao.selectSpecialSum().divide(BigDecimal.valueOf(1000),BigDecimal.ROUND_HALF_UP);

        // 创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        // 建立新的sheet对象（excel的表单）
        HSSFSheet hssfSheet = wb.createSheet("sheet1");

        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow hssfRow = hssfSheet.createRow(0);
        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell hssfCell = hssfRow.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        hssfSheet.addMergedRegion(new CellRangeAddress(2, 7, 0, 0));
        hssfSheet.addMergedRegion(new CellRangeAddress(3, 5, 3, 3));
        hssfSheet.addMergedRegion(new CellRangeAddress(3, 5, 4, 4));
        hssfSheet.addMergedRegion(new CellRangeAddress(7, 7, 1, 4));
        hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
        // 设置单元格内容
//        hssfCell.setCellValue("导出库存数据" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        hssfRow = hssfSheet.createRow(1);
        hssfRow = hssfSheet.createRow(0);
        hssfRow.createCell(0).setCellValue("忠旺机械在库物资明细");

        hssfRow = hssfSheet.createRow(1);
        hssfRow.createCell(4).setCellValue("时间："+ DateFormatUtils.format(new Date(), "yyyy-MM-dd"));

        hssfRow = hssfSheet.createRow(2);
        hssfRow.createCell(0).setCellValue("钢材库明细");
        hssfRow.createCell(1).setCellValue("类别");
        hssfRow.createCell(2).setCellValue("重量（T）");
        hssfRow.createCell(3).setCellValue("在库总量（T）");
        hssfRow.createCell(4).setCellValue("总价值（亿元）");

        hssfRow = hssfSheet.createRow(3);
        hssfRow.createCell(1).setCellValue("在干项目钢材总量");
        hssfRow.createCell(2).setCellValue(String.valueOf(oveIndexDao.getRawMaterialProjectTotalWeight().subtract(weight)));
        hssfRow.createCell(3).setCellValue(String.valueOf(oveIndexDao.getRawMaterialSteelTotalWeight()));

        hssfRow = hssfSheet.createRow(4);
        hssfRow.createCell(1).setCellValue("暂缓项目钢材总量");
        hssfRow.createCell(2).setCellValue(String.valueOf(oveIndexDao.getRawMaterialBoardTotalWeight().add(oveIndexDao.getRawMaterialProfileTotalWeight()).add(weight)));

        hssfRow = hssfSheet.createRow(5);
        hssfRow.createCell(1).setCellValue("机械常用备件");
        hssfRow.createCell(2).setCellValue(String.valueOf(oveIndexDao.getRawMaterialSparePartTotalWeight()));

        hssfRow = hssfSheet.createRow(6);
        hssfRow.createCell(1).setCellValue("手工帐");
        //输出Excel文件
        try {
            OutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + new String( "物资明细.xls".getBytes("gb2312"), "ISO8859-1" ));
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
